package com.xjprojectc.business.action;

import java.io.File;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.NumberFormat;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.xjprojectc.base.action.SysBaseAction;
import com.xjprojectc.business.pojo.T_agentaccountinfo;
import com.xjprojectc.business.pojo.T_regionalism;
import com.xjprojectc.business.service.AgentaccountinfoService;
import com.xjprojectc.business.service.RegionalismService;
import com.xjprojectc.uitl.Page;
import com.xjprojectc.webservice.Call;
import com.xjprojectc.webservice.MyFile;

/**
 * 
 * 
 * 代理商管理
 * 
 * @author Administrator
 * 
 */

@SuppressWarnings("serial")
public class AgentaccountinfoAction extends SysBaseAction {
	private AgentaccountinfoService agentaccountinfoService;
	private RegionalismService regionalismService;
	private List<T_regionalism> regionalismList;
	private T_agentaccountinfo agent;
	private List<T_agentaccountinfo> agentList;
	private String errorMsg;
	private int parame;
	private String code;
	private String msg;
	private String id;

	private File attachment; // 上传的文件
	private String attachmentFileName; // 文件名称
	private String attachmentContentType; // 文件类型

	/**
	 * 
	 * 列表页面数据处理
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String list() {
		if(agent == null){
			agent = new T_agentaccountinfo();
		}
		agent.setField4(this.getSysUser().getUsername());
		int firstResult = (currentPage - 1) * pageSize;
		int maxResults = pageSize;
		Page page = new Page(agentaccountinfoService.getPageCount(agent));
		page.setCurrentPage(firstResult / maxResults + 1);
		super.setPageInfo(page);
		agent.setStart_row(page.getStartRow());
		agent.setEnd_row(page.getStartRow() + pageSize);

		agentList = agentaccountinfoService.getAgentaccountinfoByPager(agent);

		return "list_view";
	}

	/**
	 * 
	 * 手机号码验证
	 * 
	 * @return
	 */
	public String phoneNumberVerification() {
		if (code != null) {
			agent = new T_agentaccountinfo();
			agent.setUsername(code);
			agentList = agentaccountinfoService.getAgentaccountinfoByList(agent);
			String result = "";
			if(agentList != null && agentList.size()>0){
				result = "{'success':'false','data':'该手机号码已注册！请更换手机号'}";
			}else{
				Random random = new Random();
				String pwd = "";
				String rbase[] = {"0","1", "2","3", "4", "5", "6", "7", "8", "9"};
				for (int i = 0; i < 6; i++) {
					pwd += rbase[random.nextInt(10)];
				}
				JSONObject obj = new JSONObject();
				obj.put("phoneNumber", code);
				obj.put("password", pwd);
				result = Call.getCall().exPhoneNumberVerify(obj.toString());
				System.out.println(pwd);
				this.getReqeust().getSession().setAttribute("pwdCode", pwd);
			}	
			try {
				this.jsonOut(result);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return NONE;
	}

	/**
	 * 
	 * 获取地区管理员
	 * 
	 * @return
	 */
	public String getUpagent() {
		if (code != null) {
			T_agentaccountinfo info = new T_agentaccountinfo();
			info.setBoundcode(code);
			info.setAgentlevel(1);
			agentList = agentaccountinfoService.getAgentaccountinfoByList(info);
			String result = "";
			if (agentList.size() > 0) {
				List<Map> list = new ArrayList<Map>();
				Map map = null;
				for (T_agentaccountinfo agent : agentList) {
					map = new HashMap<String, String>();
					map.put("username", agent.getUsername());
					map.put("truename", agent.getTruename());
					list.add(map);
				}
				JSONArray obj = new JSONArray();
				obj.addAll(list);
				result = "{'success':'true','data':'" + obj.toString() + "'}";
			} else {
				result = "{'success':'false','data':'该地区无法进行注册'}";
			}
			try {
				this.jsonOut(result);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return NONE;
	}
	
	
	/**
	 * 
	 * 获取地区管理员
	 * 
	 * @return
	 */
	public String getAreaBound() {
		if (code != null) {
			T_regionalism bound = new T_regionalism();
			bound.setCode(code);
			bound.setLevelnum(2);
			List<T_regionalism> bList = regionalismService.getRegionalismList(bound);
			String result = "";
			if (bList.size() > 0) {
				List<Map> list = new ArrayList<Map>();
				Map map = null;
				for (T_regionalism r : bList) {
					map = new HashMap<String, String>();
					map.put("id", r.getId());
					map.put("name", r.getName());
					list.add(map);
				}
				JSONArray obj = new JSONArray();
				obj.addAll(list);
				result = "{'success':'true','data':'" + obj.toString() + "'}";
			} else {
				result = "{'success':'false','data':'该地区无法进行注册'}";
			}
			try {
				this.jsonOut(result);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return NONE;
	}

	/**
	 * 
	 * 跳转到新增页面
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String toAdd() {
		return "input";
	}

	/**
	 * 增加
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String add() {
		if(this.getReqeust().getSession().getAttribute("pwdCode").equals(code)){
			if (attachment != null) {
				try {
					attachmentContentType = attachmentContentType.toLowerCase();
					if(attachmentContentType.toLowerCase().indexOf("bmp") > 0){
						attachmentContentType = "bmp";
					}else if(attachmentContentType.toLowerCase().indexOf("gif") > 0 ){
						attachmentContentType = "gif";
					}else if(attachmentContentType.toLowerCase().indexOf("png") > 0 ){
						attachmentContentType = "png";
					}else{
						attachmentContentType = "jpg";
					}
					
					MyFile resume = new MyFile();
					resume.setCandidateName(agent.getUsername());
					resume.setResumeFileType(attachmentContentType);
					DataSource source = new FileDataSource(attachment);
					resume.setResume(new DataHandler(source));
					Call.getFileCall().uploadFile(resume);
					
					
					//设置上级代理商和区号
					if(agent.getBoundcode() != null && !"".equals(agent.getBoundcode())){
						T_agentaccountinfo info = new T_agentaccountinfo();
						info.setBoundcode(agent.getBoundcode());
						info.setAgentlevel(1);
						List<T_agentaccountinfo> infoList = agentaccountinfoService.getAgentaccountinfoByList(info);
						if(infoList != null && infoList.size()>0){
							info = infoList.get(0);
							agent.setField4(info.getUsername());
							if(info.getCtsmsserver() != null)agent.setCtsmsserver(info.getCtsmsserver());
							if(info.getCmsmsserver() != null)agent.setCmsmsserver(info.getCmsmsserver());
							if(info.getCusmsserver() != null)agent.setCusmsserver(info.getCusmsserver());
						}
					}
					agent.setIdent_pic(agent.getUsername()+"."+attachmentContentType);
					agent.setAgentlevel(2);
					agent.setShenhe(0);
					agent.setClientmac(this.getClientMac());
					agent.setRegistertime(new Date());
					agent.setRegisterip(agent.getClientip());
					agent.setField2(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
					agent.setClientip(this.getClientIP());
					agent.setRegisterip(this.getClientIP());
					agent.setSecretkkey(java.util.UUID.randomUUID().toString().replaceAll("-", ""));
					agent.setField8("0.0");
					
					Call.getCall().exAgentRegister(JSONObject.fromObject(agent).toString());
					agentaccountinfoService.addAgentaccountinfo(agent);
					
					agent = new T_agentaccountinfo();
					msg = "注册成功，请等待管理员的审核！";
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}else{
			msg = "注册失败，手机验证码错误";
		}	
		this.getReqeust().getSession().removeAttribute("pwdCode");
		return "input";
	}

	/**
	 * 
	 * 跳转到修改页面
	 * 
	 * @return
	 */
	public String toUpdate() {
		agent = agentaccountinfoService.getOneAgentaccountinfo(id);
		return "update_view";
	}

	/**
	 * 
	 * 修改
	 * 
	 * @return
	 */
	public String update() {
		agentaccountinfoService.updateAgentaccountinfo(agent);
		return "refresh";
	}

	/**
	 * 
	 * 删除
	 * 
	 * @return
	 */
	public String del() {
		agent = new T_agentaccountinfo();
		agent.setId(Integer.parseInt(id));
		agentaccountinfoService.delAgentaccountinfo(agent);
		return "refresh";
	}
	
	
	
	public String toPwdUpdate(){
		return "pwdUpdate";
	}
	
	/**
	 * 
	 * 代理商密码修改
	 * @return
	 */
	public String pwdUpdate(){
		msg = "0";  //0 修改成功  1修改失败
		agent = this.getSysUser();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("user", Call.setCallUser(agent));
		map.put("data", code);
		JSONObject obj = new JSONObject();
		obj.putAll(map);
		try {
			String result = Call.getCall().exAgentPwdUpdate(obj.toString());
			obj = JSONObject.fromObject(result);
			if(obj.get("success").toString().equals("true")){
				agent = agentaccountinfoService.getOneAgentaccountinfoByUsername(agent.getUsername());
				agent.setPassword(code);
				agentaccountinfoService.updateAgentaccountinfo(agent);
				
				this.getReqeust().getSession().removeAttribute("sysUser");
				this.getReqeust().getSession().setAttribute("sysUser", agent);
			}else{
				msg = "1";
			}
		} catch (Exception e) {
			msg = "1";
		}
		code = "";
		return "pwdUpdate";
	}
	
	public String view(){
		agent = this.getSysUser();
		T_agentaccountinfo info = new T_agentaccountinfo();
		info.setUsername(agent.getUsername());
		agentList = agentaccountinfoService.getAgentaccountinfoByList(info);
		agent = agentList.get(0);
		if(agent.getAgentlevel() == 1){
			StringBuffer smsServerIds = new StringBuffer();
			if(agent.getCtsmsserver() != null && !"".equals(agent.getCtsmsserver())){
				smsServerIds.append("_");
				smsServerIds.append(agent.getCtsmsserver());
			}
			if(agent.getCmsmsserver() != null && !"".equals(agent.getCmsmsserver())){
				smsServerIds.append("_");
				smsServerIds.append(agent.getCmsmsserver());
			}
			if(agent.getCusmsserver() != null && !"".equals(agent.getCusmsserver())){
				smsServerIds.append("_");
				smsServerIds.append(agent.getCusmsserver());
			}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("user", Call.setCallUser(agent));
			map.put("data", smsServerIds.toString());
			JSONObject obj = new JSONObject();
			obj.putAll(map);
			String result = Call.getCall().exQuerySmsAccountBalance(obj.toString());
			obj = JSONObject.fromObject(result);
			if(obj.get("success").toString().equals("true")){
				//未找到相应短信猫
				if(!obj.get("data").toString().equals("\u672a\u77e5\u7a7a\u4e2d\u5145\u503c\u5e10\u53f7")){
					obj = JSONObject.fromObject(obj.get("data"));
					if(agent.getCtsmsserver() != null && obj.containsKey(agent.getCtsmsserver().trim())){
						agent.setCtsmsserver_money(obj.get(agent.getCtsmsserver().toString()).toString());
					}
					if(agent.getCmsmsserver() != null && obj.containsKey(agent.getCmsmsserver().trim())){
						agent.setCmsmsserver_money(obj.get(agent.getCmsmsserver().toString()).toString());
					}
					if(agent.getCusmsserver() != null && obj.containsKey(agent.getCusmsserver().trim())){
						agent.setCusmsserver_money(obj.get(agent.getCusmsserver().toString()).toString());
					}
				}	
			}
		}
		
		return "view";
	}
	
	public String expDate()
	  {
	    try
	    {
	      if (this.agent == null) {
	        this.agent = new T_agentaccountinfo();
	      }
	      this.agent.setField4(getSysUser().getUsername());
	      this.agentList = this.agentaccountinfoService.getAgentaccountinfoByList(this.agent);

	      OutputStream os = getResponse().getOutputStream();
	      this.response.reset();
	      this.response.setHeader("Content-disposition", 
	        "attachment; filename=agentList.xls");
	      this.response.setContentType("application/msexcel");

	      WritableWorkbook wbook = Workbook.createWorkbook(os);
	      String tmptitle = "代理商列表";
	      WritableSheet wsheet = wbook.createSheet(tmptitle, 0);
	      wsheet.setColumnView(0, 8);
	      wsheet.setColumnView(1, 15);
	      wsheet.setColumnView(2, 20);
	      wsheet.setColumnView(3, 15);
	      wsheet.setColumnView(4, 12);
	      wsheet.setColumnView(5, 18);
	      wsheet.setColumnView(6, 12);
	      wsheet.setColumnView(7, 18);
	      wsheet.setColumnView(8, 50);

	      WritableFont wf = new WritableFont(WritableFont.ARIAL, 12, 
	        WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, 
	        Colour.CORAL);
	      WritableCellFormat wcf = new WritableCellFormat(wf);
	      wcf.setBackground(Colour.BLUE);
	      wcf.setAlignment(Alignment.CENTRE);

	      WritableCellFormat center = new WritableCellFormat(wf);
	      center.setAlignment(Alignment.CENTRE);

	      NumberFormat doubleNunber = new NumberFormat("0.00");
	      WritableCellFormat doubleFormate = new WritableCellFormat(
	        doubleNunber);

	      NumberFormat number = new NumberFormat("00000000000");
	      WritableCellFormat nunberFormate = new WritableCellFormat(number);

	      wsheet.addCell(new Label(0, 0, "编号", wcf));
	      wsheet.addCell(new Label(1, 0, "用户名", wcf));
	      wsheet.addCell(new Label(2, 0, "真实姓名", wcf));
	      wsheet.addCell(new Label(3, 0, "联系电话", wcf));
	      wsheet.addCell(new Label(4, 0, "账户余额", wcf));
	      wsheet.addCell(new Label(5, 0, "注册时间", wcf));
	      wsheet.addCell(new Label(6, 0, "当前状态", wcf));
	      wsheet.addCell(new Label(7, 0, "最后登录时间", wcf));
	      wsheet.addCell(new Label(8, 0, "地址", wcf));

	      int num = 0;
	      Double money = Double.valueOf(0.0D);
	      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	      if ((this.agentList != null) && (this.agentList.size() > 0)) {
	        num = this.agentList.size();
	        for (int i = 0; i < num; ++i) {
	          this.agent = ((T_agentaccountinfo)this.agentList.get(i));
	          wsheet.addCell(new Label(0, i + 1, (i + 1)+""));
	          if (this.agent.getUsername() != null) {
	            wsheet.addCell(new Label(1, i + 1, this.agent.getUsername()));
	          }
	          if ((this.agent.getTruename() != null) && 
	            (!"".equals(this.agent.getTruename()))) {
	            wsheet.addCell(new Label(2, i + 1, this.agent.getTruename()));
	          }
	          if ((this.agent.getMobilephone() != null) && 
	            (!"".equals(this.agent.getMobilephone()))) {
	            wsheet.addCell(new Label(3, i + 1, this.agent.getMobilephone()));
	          }
	          if (this.agent.getAccountmoney() != null) {
	            wsheet.addCell(new Number(4, i + 1, this.agent.getAccountmoney().doubleValue(), doubleFormate));
	          }
	          if ((this.agent.getRegistertime() != null) && 
	            (!"".equals(this.agent.getRegistertime()))) {
	            wsheet.addCell(new Label(5, i + 1, sdf.format(this.agent.getRegistertime())));
	          }
	          if (this.agent.getShenhe().intValue() == 0)
	            wsheet.addCell(new Label(6, i + 1, "帐号审核中"));
	          else {
	            wsheet.addCell(
	              new Label(6, i + 1, (
	              this.agent.getLock().intValue() == 1) ? 
	              "已锁定" : "正常"));
	          }

	          if ((this.agent.getLastlogintime() != null) && 
	            (!"".equals(this.agent.getLastlogintime()))) {
	            wsheet.addCell(new Label(7, i + 1, sdf.format(this.agent.getLastlogintime())));
	          }
	          if ((this.agent.getAddr() != null) && (!"".equals(this.agent.getAddr()))) {
	            wsheet.addCell(new Label(8, i + 1, this.agent.getAddr()));
	          }
	          money = Double.valueOf(money.doubleValue() + this.agent.getAccountmoney().doubleValue());
	        }
	      }

	      wsheet.mergeCells(0, num + 1, 8, num + 1);
	      wsheet.addCell(new Label(0, num + 1, "余额总计(元):" + money, wcf));

	      wbook.write();
	      wbook.close();
	      os.close();

	      jsonOut("{'success':'true'}");
	    } catch (Exception e) {
	      e.printStackTrace();
	    }
	    return "none";
	  }

	public AgentaccountinfoService getAgentaccountinfoService() {
		return agentaccountinfoService;
	}

	public void setAgentaccountinfoService(
			AgentaccountinfoService agentaccountinfoService) {
		this.agentaccountinfoService = agentaccountinfoService;
	}

	public T_agentaccountinfo getAgent() {
		return agent;
	}

	public void setAgent(T_agentaccountinfo agent) {
		this.agent = agent;
	}

	public List<T_agentaccountinfo> getAgentList() {
		return agentList;
	}

	public void setAgentList(List<T_agentaccountinfo> agentList) {
		this.agentList = agentList;
	}

	public String getErrorMsg() {
		return errorMsg;
	}

	public void setErrorMsg(String errorMsg) {
		this.errorMsg = errorMsg;
	}

	public int getParame() {
		return parame;
	}

	public void setParame(int parame) {
		this.parame = parame;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public File getAttachment() {
		return attachment;
	}

	public void setAttachment(File attachment) {
		this.attachment = attachment;
	}

	public String getAttachmentFileName() {
		return attachmentFileName;
	}

	public void setAttachmentFileName(String attachmentFileName) {
		this.attachmentFileName = attachmentFileName;
	}

	public String getAttachmentContentType() {
		return attachmentContentType;
	}

	public void setAttachmentContentType(String attachmentContentType) {
		this.attachmentContentType = attachmentContentType;
	}

	public RegionalismService getRegionalismService() {
		return regionalismService;
	}

	public void setRegionalismService(RegionalismService regionalismService) {
		this.regionalismService = regionalismService;
	}

	public List<T_regionalism> getRegionalismList() {
		return regionalismList;
	}

	public void setRegionalismList(List<T_regionalism> regionalismList) {
		this.regionalismList = regionalismList;
	}
	
}
